package com.ddm.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.ddm.context.BaseContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * @author 丁丁猫
 * @version 1.0
 */
//配置自动填充
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
    /**
     * 自定义源数据处理器
     *
     * @param metaObject
     */
    //新增的时候填充
    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("公共字段自动填充[insert]...");
        log.info(metaObject.toString());
        if (metaObject.hasSetter("createTime")) {
            metaObject.setValue("createTime", LocalDateTime.now());
        }
        if (metaObject.hasSetter("updateTime")) {
            metaObject.setValue("updateTime", LocalDateTime.now());
        }
        //填充操作人id
        if (metaObject.hasSetter("createBy")) {
            metaObject.setValue("createBy", BaseContext.getCurrentId());
        }
        if (metaObject.hasSetter("updateBy")) {
            metaObject.setValue("updateBy", BaseContext.getCurrentId());
        }
    }
    //更新的时候填充
    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("公共字段自动填充[update]...");
        log.info(metaObject.toString());

        long id = Thread.currentThread().getId();
        log.info("线程id：{}",id);
        if (metaObject.hasSetter("updateTime")) {
            metaObject.setValue("updateTime", LocalDateTime.now());
        }
        if (metaObject.hasSetter("updateBy")) {
            metaObject.setValue("updateBy", BaseContext.getCurrentId());
        }
    }
}
